package com.deli.core.service;

import com.deli.core.dao.ProductDAO;
import com.deli.core.dao.SkuDAO;
import com.deli.core.pojo.Product;
import com.deli.core.pojo.Sku;
import com.deli.core.tools.PageHelper;
import com.github.abel533.entity.Example;

import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;

import java.io.IOException;
import java.util.List;

public class SolrToMessageListener implements MessageListener {

    @Autowired
    private ProductDAO productDAO;
    @Autowired
    private SkuDAO skuDAO;
    @Autowired
    private HttpSolrServer solrServer;


    public void onMessage(Message message) {
        ActiveMQTextMessage amessage = (ActiveMQTextMessage) message;


        String text;
		try {
			text = amessage.getText();
			System.out.println("text:" + text);
	        String[] split = text.split(",");
	        for (String id : split) {
	            Product product2 = productDAO.selectByPrimaryKey(Long.parseLong(id));
	            SolrInputDocument document = new SolrInputDocument();
	            //商品的id
	            document.addField("id", id);
	            //品牌的id
	            document.addField("brandId", product2.getBrandId());
	            //商品的名称
	            document.addField("name_ik", product2.getName());
	            String imgUrl = product2.getImgUrl().split(",")[0];
	            //品牌的首张图片
	            document.addField("url", imgUrl);
	            //select * from bbs_sku as s where s.product_id = 438 order by price asc limit 0,1;
	            Example example2 = new Example(Sku.class);
	            example2.createCriteria().andEqualTo("productId", Long.parseLong(id));
	            example2.setOrderByClause("price asc");
	            PageHelper.startPage(1, 1);
	            List<Sku> listSkus = skuDAO.selectByExample(example2);
	            PageHelper.Page<Sku> endPage = PageHelper.endPage();
	            Float price = endPage.getResult().get(0).getPrice();
	            //商品下最低价格
	            document.addField("price", price);
	            solrServer.add(document);
	            solrServer.commit();
	        }

		} catch (JMSException | SolrServerException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        

      
    }
}
